<template>
  <div class="multiplePiecesPage">
    <div class="h100 tableSearchListFlexPage taskListWarp">
      <task-list-search
        @clickbtn="handleClickSearchBtn"
        :upgrade-trigger-type="upgradeTriggerType" v-model="queryParams"
        @change="$nextTick(()=>refreshData(true))"
        :info="{ isMultiAction: this.batchOperationTag }"
        ref="taskListSearchComp"
      ></task-list-search>
      <div>
        <a-radio-group buttonStyle="solid" v-model="fromGcy" style="float:right;margin-bottom: 8px" @change="refreshData(true)">
          <a-radio-button :value="false">
            规划院
          </a-radio-button>
          <a-radio-button :value="true">
            工程院
          </a-radio-button>
        </a-radio-group>
      </div>
      <div class="tableListMain">
        <div class="h100 taskListMinheight dsxw-table-pagination-wrapper commonTableSty" ref="taskTableList">
          <div class="table-wrapper" ref="tableWrapperRef" style="min-height: 260px">
            <a-table
              ref="table"
              size="default"
              rowKey="id"
              :pagination="false"
              :columns="columns"
              :components="tableComponents"
              :dataSource="tbData"
              :row-selection="batchOperationTag ? rowSelection : null"
              :showHeader="!batchOperationTag"
              :loading="loadingPageData"
              @change="handleTableChange"
              :scroll="{ y: contentHeight, x: 1120 }"
            >
              <!-- 批量选择时表头 -->
              <template v-if="batchOperationTag" slot="title">
                <div class="tableTitle">
                  <div class="checkWarp">
                    <a-checkbox @change="allCheck" :checked="allChecked"></a-checkbox>
                  </div>
                  <div class="chosed">{{ `${$t('selected')}：${selectedRowKeys.length}` }}</div>
                  <div class="operationWarp">
                    <!-- lxhmodifyxccode--start(批量修改状态，及修改删除按钮样式) -->
                    <span>{{ $t('multiActionIs') }}：</span>
                    <a-dropdown :getPopupContainer="getPopupContainer" :trigger="['click']" class="multiChangeStatus">
                      <span class="ant-dropdown-link title" @click="(e) => e.preventDefault()">
                        {{ $t('status') }} <a-icon type="down" />
                      </span>
                      <a-menu slot="overlay" @click="handleMultiChangeStatus">
                        <a-menu-item key="suspended">
                          <a href="javascript:;">{{ $t('suspended') }}</a>
                        </a-menu-item>
                        <a-menu-item key="effectived">
                          <a href="javascript:;">{{ $t('effectived') }}</a>
                        </a-menu-item>
                        <a-menu-item key="canceled">
                          <a href="javascript:;">{{ $t('canceled') }}</a>
                        </a-menu-item>
                      </a-menu>
                    </a-dropdown>
                    <!-- 删除 -->
                    <auth-text
                      :class="{ danger: selectedRowKeys.length !== 0 }"
                      :auth="taskPerms[upgradeTriggerType.toLowerCase()].delete"
                      :disabled="selectedRowKeys.length === 0"
                      @click="deleteList()"
                    >{{ $t('delete') }}</auth-text
                    >
                    <!-- lxhmodifyxccode--end -->
                  </div>
                </div>
              </template>
              <template slot="task" slot-scope="text, record">
                <div class="taskListName">
                  <icon-with-dropdown :record="record" @action="handleClickDropdownMenu"></icon-with-dropdown>
                  <!-- 名称 -->
                  <div class="nameTag">
                    <a style="margin-right: 10px" @click="getTaskDetail(record)">
                      <table-ellipsis :text="text" @click="getTaskDetail(record)"></table-ellipsis>
                    </a>
                    <!--升级类型：自动升级手动升级 -->
                    <a-tag
                      style="height: 24px"
                      :color="record.type === 1 ? '#b18b73' : '#6ca63a'"
                      @click="handleClickTagQuery('type', record.type, 'taskTypeSelectRef', 'value', 'taskType')"
                    >
                      {{ taskTypeObj[record.type] }}
                    </a-tag>
                  </div>
                </div>
              </template>
              <!-- 升级车辆 -->
              <template slot="upgradeVehicle" slot-scope="text, record">
                <!-- {{ record.successVehicle }}/{{ record.totalVehicle }}
                <a-progress
                  :percent="parseInt((record.successVehicle / record.totalVehicle) * 100)"
                  size="small"
                  style="width:100px"
                /> -->
                <div style="position: relative">
                  <table-ellipsis
                    style="width: 30%"
                    :text="`${record.successVehicle || 0}/${record.totalVehicle || 0}`"
                  ></table-ellipsis>
                  <a-progress
                    :percent="(record.successVehicle || 0 / record.totalVehicle || 0) * 100"
                    size="small"
                    :show-info="false"
                    style="width: 70%; position: absolute; right: 0; top: 0"
                  />
                </div>
              </template>
              <!-- 任务状态 -->
              <template slot="status" slot-scope="text, record">
                <table-ellipsis :text="taskUpdateDictCodeObj[record.status] || '-'"></table-ellipsis>
              </template>
              <span slot="activationTime" slot-scope="text, record">{{ record.startTime | moment('YYYY-MM-DD') }}</span>
              <!-- 有效期 -->
              <span slot="expirationDate" slot-scope="text, record">
                <!-- 今天之前生效 今天之后失效 -->
                <table-ellipsis
                  v-if="record.endTime > new Date().getTime() && record.startTime < new Date().getTime()"
                  :text="`${formatExpirationDate(record.endTime - record.startTime)}${$t('day')} ${$t(
                    'surplusDay'
                  ).replace('__CONTENT__', formatExpirationDate(record.endTime - new Date().getTime()))}`"
                ></table-ellipsis>
                <!-- 今天之前失效 -->
                <table-ellipsis
                  v-else-if="record.endTime < new Date().getTime()"
                  :text="`${formatExpirationDate(record.endTime - record.startTime)}${$t('day')} ${$t(
                    'surplusDay'
                  ).replace('__CONTENT__', 0)}`"
                ></table-ellipsis>
                <!-- 今天之后生效 -->
                <table-ellipsis
                  v-else-if="record.startTime > new Date().getTime()"
                  :text="`${formatExpirationDate(record.endTime - record.startTime)}${$t('day')} ${$t(
                    'surplusDay'
                  ).replace('__CONTENT__', formatExpirationDate(record.endTime - record.startTime))}`"
                ></table-ellipsis>
              </span>
              <!-- 导入车辆批次号 -->
              <template slot="importBatch" slot-scope="text, record">
                <table-ellipsis :text="record.importBatch || '-'"></table-ellipsis>
              </template>
              <!-- 追加车辆状态 -->
              <template slot="importStatus" slot-scope="text, record">
                <table-ellipsis :text="importTaskVehicleStatusDictCodeObj[record.importStatus] || '-'"></table-ellipsis>
              </template>
              <template slot="createTime" slot-scope="text">
                <table-ellipsis :text="$commonFun.getDateTimeStr(text)"></table-ellipsis>
              </template>
            </a-table>
          </div>
          <div class="pagination-wrapper">
            <a-pagination
              size="small"
              :pageSizeOptions="['20', '40', '60', '80', '100']"
              :current="pageCount"
              :pageSize="pageSize"
              :total="total"
              :totalPage="totalPage"
              :showSizeChanger="true"
              :showQuickJumper="true"
              @change="changePage"
              :showTotal= "(total)=> '共'+total+'条'"
              @showSizeChange="showSizeChange"
            >
            </a-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 右侧图和查询内容 -->
    <div class="rightWarp">
      <span class="echartTitle">{{ $t('taskStatusDistribution') }}</span>
      <div class="echartWarp">
        <loadingState :echartShowStatus="distributionStatus">
          <div style="height: 340px" id="taskEchartId" class="h100"></div>
        </loadingState>
      </div>
      <div style="flex: 1 0 0; overflow-y: scroll">
        <a-tabs v-model="tabActive" @change="switchTab" class="tabCommon">
          <a-tab-pane v-for="item in tabTitles" :tab="$t(item.text)" :key="item.key">
            <component :is="tabComponent" @lastFewDays="lastFewDays" :upgradeTriggerType="upgradeTriggerType" :ref="item.text"/>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </div>
</template>
<script>
import moment from 'moment'
import { RouteView } from '@/views/layouts'
import { mapGetters, mapState, mapMutations } from 'vuex'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import distributionStatusEchart from '@/utils/echarts/loopEchart.js'
import loadingState from '@/components/SelfComponents/LoadingState'
import { minxinDrawerUse, minxinGetDomHeight } from '@/utils/mixin'
import { taskBase } from './components/MinNewTaskBase'
import IconWithDropdown from '@/views/components/IconWithDropdown'
import DetailTask from '../components/DetailTask.vue'
import MySearch from './components/MySearch.vue'
import QuickSearch from './components/QuickSearch.vue'
import TaskListSearch from './components/TaskListSearch.vue'
import AuthText from '@/components/AuthText'
import { taskPerms } from '@/config/permission/index'
import tableDraggable from '@/utils/tableDraggable'
import { columns } from './config'
import StrategyJs from "@views/strategy/strategy";
export default {
  name: 'TableList',
  mixins: [minxinDrawerUse, taskBase, minxinGetDomHeight],
  components: {
    RouteView,
    tableEllipsis,
    HasNoPermissionTip,
    loadingState,
    IconWithDropdown,
    DetailTask,
    MySearch,
    QuickSearch,
    TaskListSearch,
    AuthText
  },
  computed: {
    ...mapGetters(['myActiveProjectId']),
    ...mapState({
      taskUpdateDictCode: (state) => state.dict.taskUpdateDictCode,
      importTaskVehicleStatusDictCode: (state) => state.dict.importTaskVehicleStatusDictCode,
      // queryParams: (state) => state.task.queryParams,
      statusIcon: (state) => state.dict.taskUpdateStateObj,
      newTaskDataAll: (state) => state.newTask.newTaskData
    }),
    newTaskData(){
      return this.newTaskDataAll[this.upgradeTriggerType];
    },
    taskStatusSelect () {
      const arry = [{ value: '', name: '' }]
      return arry.concat(this.taskUpdateDictCode)
    },
    taskUpdateDictCodeObj () {
      return this.$store.getters.getDictCodeObj('taskUpdateDictCode')
    },
    importTaskVehicleStatusDictCodeObj () {
      return this.$store.getters.getDictCodeObj('importTaskVehicleStatusDictCode')
    },
    taskTypeObj () {
      return this.$store.getters.getTaskDictCodeObj('taskType')
    },
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        getCheckboxProps: this.getCheckboxProps
      }
    }
  },
  data () {
    function getTypeFromPath(path, index, vm) {
      // /task/auto-ota
      let regExp = /\/task\/(user|auto)-ota/;
      if (!regExp.test(path)) {
        vm.$message.error("找不到页面！");
        vm.$router.push("/404/inner");
        return undefined;
      }
      let match = path.match(regExp)
      let val = match[index];
      if (!val) {
        return val;
      }
      return val.toLowerCase();
    }
    return {
      queryParams: { ...this.$store.state.task.queryParams },
      fromGcy: false,
      //保留功能，但后端请求并不会区分
      upgradeTriggerType : 'AUTO',
      columns,
      taskPerms,
      tbData: [],
      pageCount: 1,
      pageSize: 20,
      total: 0,
      totalPage: 1,
      loadingPageData: false,
      partList: [],
      selectedRowKeys: [],
      selectedRows: [],
      batchOperationTag: false,
      models: [],
      distributionStatus: 3,
      allChecked: false,
      formTitle: '',
      recordData: [],
      taskStatusArr: [],
      actions: {
        // 新建任务
        crw: {
          method: 'newTaskClick'
        },
        detail: {
          method: 'getTaskDetail'
        }
      },
      tabComponent: 'QuickSearch',
      tabTitles: [
        { key: '1', text: 'quickQuery' }
        // { key: '2', text: '我的查询' }
      ],
      tabActive: '1',
      nowTime: 1560,
      wrapRef: 'tableWrapperRef',
      expectCls: '.table-wrapper .ant-table-thead',
      tableComponents: {}
    }
  },
  created () {
    const actionObj = this.actions[this.$route.query.action]
    // 从别的页面跳转过来调用相应的功能
    if (actionObj && actionObj.method) {
      this[actionObj.method]()
    }
    if(this.$route.query.taskJump){
      this.queryParams.name=this.$route.query.name
      this.refreshData()
    }
    this.filterItem()
    this.getPageDictData()
    this.tableComponents = tableDraggable(this.columns)
  },
  mounted () {
    const vm = this
    vm.$nextTick(() => {
      vm.initEcharts()
    })
    // 加载页面时初始化之前的筛选值
    this.clearCondition()
    this.distributionStatusDate()
  },
  activated(){
    this.distributionStatusDate();
  },
  methods: {
    ...mapMutations(['setInstantUpdateTime', 'RESET_NEWTASK_DATA']),
    getPopupContainer () {
      return document.body
    },
    // 格式化有效时间
    formatExpirationDate (time) {
      return Math.ceil(time / 1000 / 24 / 60 / 60)
    },
    // 点击列表中tag查询
    handleClickTagQuery (queryKey, val, ref, itemKey = 'value', optionKey = 'options') {
      const value = val + ''
      if (ref) {
        // 说明是在隐藏的搜索组件里面
        this.$refs.taskListSearchComp.handleSelectOption(ref, queryKey, value, itemKey, optionKey)
      } else {
        this.queryParams[queryKey] = val
      }
      this.refreshData()
    },
    // 表头排序处理
    handleTableChange (pagination, filters, sorter) {
      if (sorter && sorter.columnKey) {
        this.sortedInfo = sorter
        const findIndex = this.columns.findIndex((item) => item.key === sorter.columnKey)
        if (sorter.order) {
          const orderType = {
            ascend: 'ASC',
            descend: 'DESC'
          }
          this.queryParams.order = `${sorter.columnKey},${orderType[sorter.order]}`
          this.$set(this.columns[findIndex], 'sortOrder', sorter.order)
        } else {
          this.queryParams.order = undefined
          this.$set(this.columns[findIndex], 'sortOrder', false)
        }
        this.refreshData()
      }
    },
    // 处理搜索组件中的单击事件
    handleClickSearchBtn (data) {
      this.nowTime = Date.now()
      if (this[data.type]) {
        this[data.type]()
      }
    },
    // 清空
    clearCondition () {
      this.$store.commit('resetTaskQueryParams')
      this.queryParams = {...this.$store.state.task.queryParams};    // 触发
      // Object.assign(this.queryParams, {...this.$store.state.task.queryParams});    // 触发
      this.$refs.taskListSearchComp.queryParamsDesc = {}
      this.sortedInfo = null
      this.refreshData()
    },
    // 批量操作切换
    toggleMultiAction () {
      this.rowSelection.onChange([], []) // 不记忆上一次勾选
      this.batchOperationTag = !this.batchOperationTag
    },
    // 获取页面所需要的字典
    getPageDictData () {
      const dicts = ['getTaskUpdateDictCodeData','getImportTaskVehicleStatusDictCodeData']
      dicts.forEach((method) => {
        this.$store.dispatch(method)
      })
    },
    // 全选操作
    allCheck (e) {
      this.selectedRowKeys = []
      if (e.target.checked) {
        this.tbData.forEach(e=>{
          if (e.status !== 16 && e.status !== 17 && e.status !== 18) {
            this.selectedRowKeys.push(e.id);
          }
        })
        this.allChecked = true
      } else {
        this.allChecked = false
      }
    },
    // 筛选条件
    filterItem () {
      const vm = this
      //   获取所有零件
      vm.$api.getAllEcu().then((res) => {
        vm.partList = res.data
      })
    },
    // 格式化筛选时间
    formatParamTime (JnqueryParam) {
      const formatArry = ['enableTimeGte', 'enableTimeLte', 'createTimeGte', 'createTimeLte']
      // eslint-disable-next-line no-restricted-syntax
      for (const item in JnqueryParam) {
        if (formatArry.includes(item) && JnqueryParam[item]) {
          // eslint-disable-next-line no-param-reassign
          JnqueryParam[item] = moment(JnqueryParam[item]).format('YYYY-MM-DD')
        }
      }
    },
    loadPageData () {
      const vm = this
      // 如果是全部则不传值给后端
      return new Promise((resolve, reject) => {
        const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParams))
        // eslint-disable-next-line no-restricted-syntax
        for (const key in JnqueryParam) {
          if (!JnqueryParam[key]) {
            JnqueryParam[key] = undefined
          }
        }
        vm.formatParamTime(JnqueryParam)
        JnqueryParam.projectIds = vm.myActiveProjectId
        // JnqueryParam.type = this.upgradeTriggerType === 'USER' ? 1 : 2;
        vm.loadingPageData = true
        vm.$api
          .getTaskPageData({ pageNo: vm.pageCount, pageSize: vm.pageSize, ...JnqueryParam, fromGcy: this.fromGcy })
          .then((res) => {
            const { data } = res
            // if (this.pageCount > 1) {
            //   data = this.tbData.concat(data)
            // }
            this.tbData = data
            this.total = res.totalCount
            this.totalPage = res.totalPage
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
          .finally(() => {
            vm.loadingPageData = false
          })
      })
    },
    refreshData (bool = true) {
      if (bool) {
        this.pageCount = 1
      }
      this.loadPageData()
      this.$refs.quickQuery[0].getList();
    },
    changePage (page) {
      this.pageCount = page
      this.loadPageData()
    },
    showSizeChange (current, size) {
      this.pageSize = size
      this.pageCount = 1
      this.loadPageData()
    },
    // 删除
    deleteList () {
      const vm = this
      let arr = []
      let selectedArr = []
      this.tbData.forEach(e=>{
        if(this.selectedRowKeys.indexOf(e.id) != -1) {
            selectedArr.push(e)
      }
      })
      selectedArr.forEach(i=>{
          if (i.status !== 16 && i.status !== 17 && i.status !== 18) {
            arr.push(i.name);
          }
       })
      this.$confirm({
        title: vm.$t('deleteCampaign'),
        content: vm.$t('deleteCampaignTip' + `(${arr.join('，')})`),
        onOk () {
          vm.$api.delateTaskData({ ids: vm.selectedRowKeys }, 'uat').then(() => {
            vm.$message.success(vm.$t('successfullyDelete'))
            vm.filterItem()
            vm.rowSelection.onChange([], []) // 清空已选择
            vm.refreshData()
          })
        },
        onCancel () {}
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      // if (this.selectedRowKeys.length === this.tbData.length) {
      //   this.allChecked = true
      // } else {
      //   this.allChecked = false
      // }
      selectedRows = selectedRows.filter((record) => {
        return record.status !== 16 && record.status !== 17 && record.status !== 18;
      })
      selectedRowKeys = selectedRows.map((record) => record.id)
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    getCheckboxProps: (record) => ({
      // 已失效和已取消不能勾选
      props: {
        disabled: record.channel === 0 || record.status === 16 || record.status === 17 || record.status === 18
      }
    }),
    // 新建任务
    newTaskClick () {
      const vm = this
      // vm.SET_UPGRADE_TRIGGER_TYPE(this.upgradeTriggerType)
      // vm.RESET_NEWTASK_DATA() // 新建时先清除缓存
      vm.getCurrentStepConfig(vm.stepNum)
      vm.toggleDrawerMain(true)
      vm.setDefaultName()
      // 清除第三个任务审核审批用户设置数据
      sessionStorage.removeItem('nodeOfApprovalObj')
    },
    // 生成任务默认名称BUG202209091501_51200 lxhmodifyxccode
    setDefaultName () {
      const name = this.$t('otaUpdateTask')
      this.newTaskData.name = `${name}[${this.$commonFun.getDateMinuteStr(new Date())}]`
      this.newTaskData.taskGcyExt.batchName = this.newTaskData.name
    },
    // 查看任务详情
    getTaskDetail (record) {
      const buttons = []
      // this.SET_UPGRADE_TRIGGER_TYPE(this.upgradeTriggerType)
      this.showRightDrawer(DetailTask, record.name, buttons, 'huge', {
        taskId: record.id,
        type: record.type,
        taskStatus: record.status,
        upgradeTriggerType:this.upgradeTriggerType
      })
    },
    // 取消
    handelCancel (record) {
      // lxhmodifyxccode
      if (!this.checkEditStatusRole()) {
        return
      }
      const vm = this
      this.$confirm({
        title: vm.$t('systemTip'),
        content: vm.$t('newCancelTaskTip').replace('__TaskName__', record.name),
        onOk () {
          vm.$api.cancelTask({ ids: [record.id] }, 'uat').then(() => {
            vm.afterDoAction()
          })
        },
        onCancel () {}
      })
    },
    // 取消并删包
    handelCancelAndDeletePackage (record) {
      // lxhmodifyxccode
      if (!this.checkEditStatusRole()) {
        return
      }
      const vm = this
      this.$confirm({
        title: vm.$t('systemTip'),
        content: vm.$t('newCancelTaskTip').replace('__TaskName__', record.name),
        onOk () {
          vm.$api.cancelAndDeletePackage({ ids: [record.id] }, 'uat').then(() => {
            vm.afterDoAction()
          })
        },
        onCancel () {}
      })
    },
    // 挂起或者进行中
    handleStopStart (record, enabled) {
      // lxhmodifyxccode
      if (!this.checkEditStatusRole()) {
        return
      }
      const vm = this
      this.$confirm({
        title: vm.$t('systemTip'),
        // eslint-disable-next-line max-len
        content: enabled ? vm.$t('continueTaskTip').replace('__TaskName__', record.name) : vm.$t('pauseTaskTip').replace('__TaskName__', record.name),
        onOk () {
          vm.$api.stopOrStart({ ids: [record.id], enabled: enabled }, 'uat').then(() => {
            vm.afterDoAction()
          })
        },
        onCancel () {}
      })
    },
    // 催办
    presstodo (record) {
      if (!this.$hasPermission([taskPerms.operate])) {
        this.$message.error(this.$t('noOperateStatusRoleTip'))
        return
      }
      const vm = this
      vm.$api.urgeMyApply({ instanceId: record.instanceId }).then(() => {
        vm.afterDoAction()
      })
    },
    // 任务列表操作成功后
    afterDoAction () {
      const vm = this
      vm.$message.success(vm.$t('successfullyOperation'))
      vm.refreshData(false)
      vm.distributionStatusDate() // 更新饼图
      // vm.setInstantUpdateTime()
    },
    // echart
    distributionStatusDate () {
      const vm = this
      this.distributionStatus = 1
      vm.$api
        .getTaskCountByStatus({ projectIds: vm.myActiveProjectId })
        .then((Response) => {
          if (Response.data) {
            vm.distributionStatus = 2
            distributionStatusEchart.setEchart(vm.distributionStatusDom)
            const echartData = []
            var a=[]
            a=Response.data
            // if(this.upgradeTriggerType === 'USER'){
            //   console.log(this.upgradeTriggerType,'USER')
            //
            //    a=Response.data
            // }else{
            //   console.log(this.upgradeTriggerType,'AUTO')
            //   a=Response.data.filter(item=>item.key!=='18')
            // }
            a.forEach((item) => {
              echartData.push({
                name: vm.taskUpdateDictCodeObj[item.key],
                key: item.key,
                value: item.count,
                itemStyle: {
                  color: vm.statusIcon[item.key].color
                }
              })
            })
            vm.distributionStatusDom.setOption({
              legend: {
                bottom: '10',
                left: 'left'
                // orient: 'vertical',
                // top: 'middle'
              },
              series: [
                {
                  data: echartData
                }
              ]
            })
          } else {
            vm.distributionStatus = 3
          }
        })
        .catch(() => {
          this.distributionStatus = 3
        })
    },
    // 我的查询和快速查询切换
    switchTab (value) {
      if (value === '1') {
        this.tabComponent = 'QuickSearch'
      } else if (value === '2') {
        this.tabComponent = 'MySearch'
      }
      this.tabActive = value
    },
    // 近几日推算
    lastFewDays (value, type) {
      const nowTime = moment(new Date().getTime().valueOf())
      this.queryParams.createTimeLte = null
      this.queryParams.createTimeGte = null
      this.queryParams.enableTimeLte = null
      this.queryParams.enableTimeGte = null
      console.log(value, type)
      const dayStep = value - 1
      if (type === '1') {
        // 创建时间止
        this.queryParams.createTimeLte = `${nowTime.format('YYYY-MM-DD')}`
        //   创建时间起
        this.queryParams.createTimeGte = `${nowTime.add(-dayStep, 'days').format('YYYY-MM-DD')}`
      } else {
        // 生效时间止
        this.queryParams.enableTimeLte = `${nowTime.format('YYYY-MM-DD')}`
        //   生效时间起
        this.queryParams.enableTimeGte = `${nowTime.add(-dayStep, 'days').format('YYYY-MM-DD')}`
      }

      this.refreshData()
    },
    // 初始化任务状态分布图
    initEcharts () {
      const vm = this
      vm.distributionStatusDom = vm.$echarts.init(document.getElementById('taskEchartId'))
      this.bindEchartEvent()
    },
    bindEchartEvent () {
      const vm = this
      window.addEventListener('resize', this.resizeEchart)
      this.distributionStatusDom.on('click', (param) => {
        vm.$set(vm.queryParams, 'status', param.data.key)
        vm.refreshData()
      })
    },
    resizeEchart () {
      const vm = this
      vm.distributionStatusDom && vm.distributionStatusDom.resize()
    },
    handleClickDropdownMenu (obj) {
      if (this[obj.type]) {
        this[obj.type](obj.record, obj.other)
      }
    },
    // 批量修改状态 lxhmodifyxccode
    handleMultiChangeStatus ({ key }) {
      if (!this.selectedRowKeys.length) {
        this.$message.warning(this.$t('pleaseSelect') + ' ' + this.$t('campaign').toLowerCase())
        return
      }
      if (!this.checkEditStatusRole()) {
        return
      }
      const config = {
        suspended: {
          value: 13,
          method: 'multiHandleStopStart',
          data: { ids: [...this.selectedRowKeys], enabled: false }
        },
        effectived: {
          value: 12,
          method: 'multiHandleStopStart',
          data: { ids: [...this.selectedRowKeys], enabled: true }
        },
        canceled: {
          value: 16,
          method: 'multiHandelCancel',
          data: { ids: [...this.selectedRowKeys] }
        }
      }
      const current = config[key]
      this[current.method](current.data)
    },
    // 批量已挂起或已生效 lxhmodifyxccode
    multiHandleStopStart (data) {
      const vm = this
      vm.$api.stopOrStart(data, 'uat').then(() => {
        vm.afterDoAction()
        vm.rowSelection.onChange([], []) // 清空已选择
      })
    },
    // 批量取消 lxhmodifyxccode
    multiHandelCancel (data) {
      const vm = this
      vm.$api.cancelTask(data, 'uat').then(() => {
        vm.afterDoAction()
        vm.rowSelection.onChange([], []) // 清空已选择
      })
    },
    // lxhmodifyxccode 检测是否拥有修改任务的权限
    checkEditStatusRole () {
      if (!this.$hasPermission([taskPerms[this.upgradeTriggerType.toLowerCase()].edit])) {
        this.$message.error(this.$t('noEditStatusRoleTip'))
        return false
      }
      return true
    }
  },
  watch: {
    taskUpdateDictCode: {
      handler (val) {
        if (val.length) {
          this.distributionStatusDate()
        }
      },
      immediate: true
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resizeEchart)
  }
}
</script>
<style lang="less">
.taskListMinheight {
  .ant-table-wrapper {
    .ant-table-content {
      .ant-table-body {
        min-height: 200px !important;
      }
    }
    .ant-table-empty .ant-table-content {
      .ant-table-body {
        min-height: 0px !important;
      }
    }
  }
}
</style>
<style lang="less" scoped>
.taskListName {
  position: relative;
  .nameTag {
    padding-left: 26px;
    display: flex;
    .ant-tag {
      height: 22px;
    }
  }
}
.deleteBtn {
  font-size: 0.8rem;
  height: 26px;
  line-height: 26px;
  padding: 0;
  text-align: center;
  min-width: 58px;
}
.lastActiveTag {
  color: #2bb080;
  background: #fff;
  border-color: #2bb080;
}
.lastUpgradeTag {
  color: @primary-color;
  background: #fff;
  border-color: @primary-color;
}
.taskListWarp {
  width: calc(100% - 360px);
}
.rightWarp {
  width: 360px;
  padding: 24px;
  border-left: 1px solid #f2f2f2;
  background: #fff;
  display: flex;
  flex-direction: column;
  .echartTitle {
    font-size: 1.8rem;
    color: #5e5e5e;
    font-weight: bolder;
  }
  .echartWarp {
    border-bottom: 1px solid #f2f2f2;
  }
}
.multiChangeStatus {
  margin-right: 16px;
  .title {
    cursor: pointer;
  }
}
.danger:not(.disabledAuthTextWrap) {
  color: #ff3737;
}
</style>
